package com.zmn.oms.business.impl.track;

import com.zmn.oms.business.interfaces.mq.MqProviderService;
import org.apache.dubbo.config.annotation.Reference;
import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.business.interfaces.track.OrderTrackBService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.model.dto.track.AddOrderTrackDTO;
import com.zmn.oms.model.dto.track.CompleteOrderTrackDTO;
import com.zmn.oms.model.dto.track.OrderTrackDTO;
import com.zmn.oms.model.dto.track.OrderTrackDetailDTO;
import com.zmn.oms.model.entity.masterworking.MasterWorking;
import com.zmn.oms.model.entity.track.OrderTrack;
import com.zmn.oms.model.entity.track.OrderTrackQuery;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.track.OrderTrackVO;
import com.zmn.oms.services.interfaces.masterworking.MasterWorkingService;
import com.zmn.oms.services.interfaces.track.OrderTrackService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.services.interfaces.work.masterwork.MasterWorkService;
import io.shardingsphere.core.keygen.DefaultKeyGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：跟单实现类
 *
 * @author heciqi
 * @date 2018/11/27 11:15
 */
@Service
@Deprecated
public class OrderTrackBServiceImpl implements OrderTrackBService {

	private Logger logger = LoggerFactory.getLogger(OrderTrackBServiceImpl.class);

	@Autowired
	private OrderTrackService orderTrackService;
	@Autowired
	private MasterWorkService masterWorkService;
	@Autowired
	private MasterWorkingService masterWorkingService;
	@Autowired
	private OrderWorkService orderWorkService;
	@Autowired
	private DefaultKeyGenerator defaultKeyGenerator;
	@Autowired
	private OrderTrackBService orderTrackBService;
	//@Reference(version = com.zmn.base.engineer.common.constants.DubboConsts.INTERFACE_VERSION, check = false)
	//private EngineerTouchModifyRemoteService engineerTouchModifyRemoteService;

	@Autowired
	private MqProviderService mqProviderService;

	@Override
	public List<OrderTrackVO> listUnCompleteOrderTrackByOrderId(Long orderId, Long workId) {
		List<OrderTrack> orderTrackList = orderTrackService.listOrderTrackByWorkId(orderId, workId);
		List<OrderTrack> unCompleteOrderTrackList = orderTrackList.stream()
				.filter(orderTrack -> Objects.equals(orderTrack.getComplete(), GlobalConsts.NO))
				.collect(Collectors.toList());
		return BeanMapper.mapList(unCompleteOrderTrackList, OrderTrackVO.class);
	}

	/**
	 * 数量查询
	 *
	 * @param query
	 * @return
	 */
	@Override
	public Integer countByQuery(OrderTrackQuery query) {
		return orderTrackService.countByQuery(query);
	}

	/**
	 * 新增工程师跟单
	 *
	 * @param addOrderTrackDTO
	 * @return
	 */
	@Override
	public void insertMasterTrack(AddOrderTrackDTO addOrderTrackDTO) {
		// 新增工单
		OrderTrack orderTrack = new OrderTrack();
		orderTrack.setOrderId(addOrderTrackDTO.getOrderId());
		orderTrack.setWorkId(addOrderTrackDTO.getWorkId());
		orderTrack.setAddUserId(addOrderTrackDTO.getAddUserId());
		orderTrack.setAddUserType(GlobalConsts.PLAT_OBJ_TYPE_MASTER);
		orderTrack.setMapId(addOrderTrackDTO.getMapId());
		orderTrack.setMapName(addOrderTrackDTO.getMapName());
		orderTrack.setRemark(addOrderTrackDTO.getRemark());
		orderTrack.setCreateTime(new Date());
		orderTrackService.insertTrack(orderTrack);

		// 更新工单跟单状态
		this.updateOrderWorkTrackStatus(orderTrack, OrderConsts.ORDER_TRACK_STATUS_DOING);
	}

	/**
	 * 新增后台用户跟单
	 *
	 * @param addOrderTrackDTO
	 * @return
	 */
	@Override
	public void insertUserTrack(AddOrderTrackDTO addOrderTrackDTO) {
		// 新增工单
		OrderTrack orderTrack = new OrderTrack();
		orderTrack.setOrderId(addOrderTrackDTO.getOrderId());
		orderTrack.setWorkId(addOrderTrackDTO.getWorkId());
		orderTrack.setAddUserId(addOrderTrackDTO.getAddUserId());
		orderTrack.setAddUserType(GlobalConsts.PLAT_OBJ_TYPE_STAFF);
		orderTrack.setMapId(addOrderTrackDTO.getMapId());
		orderTrack.setMapName(addOrderTrackDTO.getMapName());
		orderTrack.setRemark(addOrderTrackDTO.getRemark());
		orderTrack.setCreater("");// TODO-HCQ-操作用户名称
		orderTrack.setCreateTime(new Date());
		orderTrackService.insertTrack(orderTrack);

		// 更新工单跟单状态
		this.updateOrderWorkTrackStatus(orderTrack, OrderConsts.ORDER_TRACK_STATUS_DOING);
	}

	/**
	 * 修改跟单结果
	 *
	 * @param completeOrderTrackDTO
	 * @return
	 */
	@Override
	public void updateResultTrack(CompleteOrderTrackDTO completeOrderTrackDTO) {
		OrderTrack orderTrack = new OrderTrack();
		orderTrack.setTrackId(completeOrderTrackDTO.getTrackId());
		orderTrack.setOrderId(completeOrderTrackDTO.getOrderId());
		orderTrack.setWorkId(completeOrderTrackDTO.getWorkId());
		orderTrack.setCompleteUserType(GlobalConsts.PLAT_OBJ_TYPE_STAFF);
		orderTrack.setCompleteUserId(completeOrderTrackDTO.getCompleteUserId());
		orderTrack.setResultContent(completeOrderTrackDTO.getResultContent());
		orderTrack.setComplete(1);
		orderTrack.setCompleteTime(new Date());
		orderTrackService.updateResultTrack(orderTrack);

		// 更新工单跟单状态
		this.updateOrderWorkTrackStatus(orderTrack, OrderConsts.ORDER_TRACK_STATUS_DONE);
	}

	@Override
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_TRACK, beforeProceed = true)
    @Transactional(rollbackFor = Exception.class)
    public void updateTrack(OrderTrackDTO orderTrackDTO){
		List<OrderTrackDetailDTO> detailDTOList = orderTrackDTO.getDetailDTOList();

		// 新增跟单
		List<OrderTrack> addList = Lists.newArrayList();
		// 完成跟单
		List<OrderTrack> completeList = Lists.newArrayList();
		// 删除跟单
		List<Long> deleteTrackIdList = Lists.newArrayList();
		// 进行中跟单
		List<OrderTrack> doingList = Lists.newArrayList();

		for (OrderTrackDetailDTO detailDTO : detailDTOList) {
			Long trackId = detailDTO.getTrackId();
			String resultContent = detailDTO.getResultContent();
			Integer deleted = detailDTO.getDeleted();

			OrderTrack orderTrack = new OrderTrack();
			orderTrack.setOrderId(orderTrackDTO.getOrderId());
			orderTrack.setWorkId(orderTrackDTO.getWorkId());

			// 删除
			if (Objects.equals(deleted, GlobalConsts.YES)) {
				if (Objects.nonNull(trackId)) {
					deleteTrackIdList.add(trackId);
				}
			// 新增
			} else {
				int userId = Optional.ofNullable(orderTrackDTO.getOperatorId()).orElse(0L).intValue();

				if (Objects.isNull(trackId)) {
					long generateKey = defaultKeyGenerator.generateKey().longValue();
					detailDTO.setTrackId(generateKey);
					detailDTO.setIsNew(GlobalConsts.YES);
					orderTrack.setTrackId(generateKey);
					orderTrack.setAddUserId(userId);
					orderTrack.setAddUserType(orderTrackDTO.getOperatorType());
					orderTrack.setAddUserName(orderTrackDTO.getOperator());
					orderTrack.setCreater(orderTrackDTO.getOperator());
					orderTrack.setMapId(detailDTO.getMapId());
					orderTrack.setMapName(detailDTO.getMapName());
					orderTrack.setLevel(detailDTO.getLevel());
					orderTrack.setRemark(detailDTO.getRemark());
					if (StringUtil.isNotBlank(detailDTO.getResultContent())) {
						orderTrack.setResultContent(resultContent);
						orderTrack.setCompleteUserId(userId);
						orderTrack.setCompleteUserName(orderTrackDTO.getOperator());
						orderTrack.setCompleteUserType(orderTrackDTO.getOperatorType());
						orderTrack.setComplete(GlobalConsts.YES);
						orderTrack.setCompleteTime(DateUtil.getNow());
					} else {
						orderTrack.setComplete(GlobalConsts.NO);
					}
					addList.add(orderTrack);

				// 完成
				} else if (Objects.nonNull(trackId) && StringUtil.isNotBlank(resultContent)) {
					orderTrack.setTrackId(trackId);
					orderTrack.setResultContent(resultContent);
					orderTrack.setCompleteUserId(userId);
					orderTrack.setCompleteUserName(orderTrackDTO.getOperator());
					orderTrack.setCompleteUserType(orderTrackDTO.getOperatorType());
					orderTrack.setComplete(GlobalConsts.YES);
					orderTrack.setCompleteTime(DateUtil.getNow());
					completeList.add(orderTrack);

				// 进行中
				} else {
					orderTrack.setTrackId(trackId);
					doingList.add(orderTrack);
				}
			}
		}

		// 删除跟单数据
		if (!deleteTrackIdList.isEmpty()) {
			orderTrackService.deleteByTrackIdList(deleteTrackIdList);
		}

		// 新增跟单数据
		if (!addList.isEmpty()) {
			List<OrderTrack> addCompleteTrackList = addList.stream().filter(e -> StringUtil.isNotBlank(e.getResultContent())).collect(Collectors.toList());
			List<OrderTrack> addTrackList = addList.stream().filter(e -> StringUtil.isBlank(e.getResultContent())).collect(Collectors.toList());
			orderTrackService.insertTrackList(addTrackList);
			orderTrackService.insertCompleteTrackList(addCompleteTrackList);
		}

		// 跟单完成数据
		if (!completeList.isEmpty()) {
			completeList.forEach(complete -> orderTrackService.updateResultTrack(complete));
		}

		// 待件状态
		Integer waitPart;
		// 待取消状态
		Integer waitCancel;
		// 拉修状态
		Integer delivery;
		// 跟单状态
		Integer trackStatus = OrderConsts.ORDER_TRACK_STATUS_NONE;

		// 主库查询 跟单记录
		List<OrderTrack> orderTrackList = orderTrackService.listOrderTrackByWorkIdSrcMaster(orderTrackDTO.getOrderId(), orderTrackDTO.getWorkId());

		// 是否有新的待件跟单
		boolean hasWaitPart = orderTrackList.stream().anyMatch(e -> Objects.equals(e.getMapId(), OrderConsts.ORDER_TRACT_TYPE_WAIT_PART_ID) && Objects.equals(e.getComplete(), GlobalConsts.NO));
		waitPart = hasWaitPart ? GlobalConsts.YES : GlobalConsts.NO;

		// 是否有新的拉修跟单
		boolean hasDelivery = orderTrackList.stream().anyMatch(e -> Objects.equals(e.getMapId(), OrderConsts.ORDER_TRACT_TYPE_DELIVERY_ID) && Objects.equals(e.getComplete(), GlobalConsts.NO));
		delivery = hasDelivery ? GlobalConsts.YES : GlobalConsts.NO;

		// 是否有新的待取消跟单
		boolean hasWaitCancel = orderTrackList.stream().anyMatch(e -> Objects.equals(e.getMapId(), OrderConsts.ORDER_TRACT_TYPE_FAIL_APPLY_ID) && Objects.equals(e.getComplete(), GlobalConsts.NO));
		waitCancel = hasWaitCancel ? GlobalConsts.YES : GlobalConsts.NO;

		// 有进行中的
		boolean hasDoing = orderTrackList.stream().anyMatch(e -> Objects.equals(e.getComplete(), GlobalConsts.NO));

		// 如果没有进行中和新增则状态
		if (hasDoing) {
			trackStatus = OrderConsts.ORDER_TRACK_STATUS_DOING;
		} else if (!orderTrackList.isEmpty()) {
			trackStatus = OrderConsts.ORDER_TRACK_STATUS_DONE;
		}

		// 后台操作待失败申请跟单师傅app刷新版本号
		List<Integer> refreshList = Arrays.asList(OrderConsts.ORDER_TRACT_TYPE_FAIL_APPLY_ID, OrderConsts.ORDER_TRACT_TYPE_WAIT_PART_ID, OrderConsts.ORDER_TRACT_TYPE_DELIVERY_ID);
		boolean refresh = orderTrackDTO.getDetailDTOList().stream().anyMatch(e -> refreshList.contains(e.getMapId()));
		if(refresh){
			MasterWorking masterWorkingByWorkId = masterWorkingService.findMasterWorkingByWorkId(orderTrackDTO.getWorkId());
			if (masterWorkingByWorkId != null) {
				// 刷新工程师工单列表版本号
				//engineerTouchModifyRemoteService.saveEngineerWorkVersion(masterWorkingByWorkId.getMasterId(), null);
				mqProviderService.sendEngineerWorkVersion(masterWorkingByWorkId.getMasterId(), null);
			}
		}

		// 更新工单跟单数据
		OrderWork orderWork = new OrderWork();
		orderWork.setOrderId(orderTrackDTO.getOrderId());
		orderWork.setWorkId(orderTrackDTO.getWorkId());
		orderWork.setWaitPart(waitPart);
		orderWork.setDelivery(delivery);
		orderWork.setTrackStatus(trackStatus);
		orderWork.setCurrentRemark(orderTrackDTO.getOperatorLogRemark());
		masterWorkService.updateTrackStatus(orderWork);

		// 同步进行中的工程师工单表
		masterWorkingService.updateMasterWorkingStatus(orderTrackDTO.getWorkId(), delivery, waitPart, waitCancel);
	}

	/**
	 * 更新工单跟单状态
	 * @param orderTrack
	 * @param trackStatus
	 */
	private void updateOrderWorkTrackStatus(OrderTrack orderTrack,Integer trackStatus) {
		if (orderTrack.getOrderId() == null || orderTrack.getWorkId() == null) {
			logger.warn("工单id或订单id参数不存在!");
			return;
		}

		OrderWork orderWork = new OrderWork();
		orderWork.setOrderId(orderTrack.getOrderId());
		orderWork.setWorkId(orderTrack.getWorkId());
		orderWork.setTrackStatus(trackStatus);
		masterWorkService.updateTrackStatus(orderWork);
	}

	/**
	 * 完成所有跟单并塞日志
	 * @param orderId
	 * @param workId
	 * @param resultContent
	 */
	@Override
	public void completeAllTrack(Long orderId, Long workId, String resultContent){

		// 主库查询 跟单记录
		List<OrderTrack> orderTrackList = orderTrackService.listOrderTrackByWorkIdSrcMaster(orderId, workId);

		// 过滤未完成跟单
		List<OrderTrack> uncompletedList = orderTrackList.stream().filter(orderTrack -> Objects.equals(orderTrack.getComplete(), GlobalConsts.NO)).collect(Collectors.toList());

		if (CollectionUtil.isNullOrEmpty(uncompletedList)) {
			return;
		}
		OrderTrackDTO orderTrackDTO = new OrderTrackDTO();

		orderTrackDTO.setOrderId(orderId);
		orderTrackDTO.setWorkId(workId);
		orderTrackDTO.setComplete(GlobalConsts.YES);
		orderTrackDTO.setOperator("系统");
		orderTrackDTO.setOperatorId(0L);
		orderTrackDTO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
		List<OrderTrackDetailDTO> detailDTOList = new ArrayList<>(uncompletedList.size());

		for (OrderTrack orderTrack : uncompletedList) {
			OrderTrackDetailDTO detailDTO = BeanMapper.map(orderTrack, OrderTrackDetailDTO.class);
			detailDTO.setResultContent(resultContent);
			detailDTOList.add(detailDTO);
		}

		orderTrackDTO.setDetailDTOList(detailDTOList);

		orderTrackBService.updateTrack(orderTrackDTO);
	}
}
